package com.umeng.comm.ui.fragments;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qianxx.base.utils.LogUtil;
import com.qianxx.base.utils.SPUtil;
import com.qianxx.base.utils.StringUtil;
import com.qianxx.base.utils.TimeUtil;
import com.umeng.comm.core.CommunitySDK;
import com.umeng.comm.core.beans.CommConfig;
import com.umeng.comm.core.beans.CommUser;
import com.umeng.comm.core.beans.FeedItem;
import com.umeng.comm.core.constants.Constants;
import com.umeng.comm.core.imageloader.ImgDisplayOption;
import com.umeng.comm.core.impl.CommunityFactory;
import com.umeng.comm.core.impl.CommunitySDKImpl;
import com.umeng.comm.core.listeners.Listeners;
import com.umeng.comm.core.login.LoginListener;
import com.umeng.comm.core.nets.responses.ProfileResponse;
import com.umeng.comm.core.nets.uitls.NetworkUtils;
import com.umeng.comm.core.sdkmanager.ImageLoaderManager;
import com.umeng.comm.core.utils.CommonUtils;
import com.umeng.comm.core.utils.DeviceUtils;
import com.umeng.comm.core.utils.ResFinder;
import com.umeng.comm.ui.activities.FavoritesActivity;
import com.umeng.comm.ui.activities.FollowedTopicActivity;
import com.umeng.comm.ui.activities.SetActivity;
import com.umeng.comm.ui.imagepicker.activities.MessageChatActivity;
import com.umeng.comm.ui.imagepicker.activities.SettingActivity;
import com.umeng.comm.ui.imagepicker.anim.CustomAnimator;
import com.umeng.comm.ui.imagepicker.anim.UserInfoAnimator;
import com.umeng.comm.ui.imagepicker.dialogs.UserReportDialog;
import com.umeng.comm.ui.imagepicker.fragments.BaseFragment;
import com.umeng.comm.ui.imagepicker.fragments.FansFragment;
import com.umeng.comm.ui.imagepicker.mvpview.MvpUserInfoView;
import com.umeng.comm.ui.imagepicker.presenter.impl.NullPresenter;
import com.umeng.comm.ui.imagepicker.presenter.impl.UserInfoPresenter;
import com.umeng.comm.ui.imagepicker.util.BroadcastUtils;
import com.umeng.comm.ui.imagepicker.util.UserTypeUtil;
import com.umeng.comm.ui.imagepicker.widgets.CommentEditText;
import com.umeng.comm.ui.imagepicker.widgets.RoundImageView;
import com.umeng.comm.ui.imagepicker.widgets.SquareImageView;
import com.umeng.community.example.Utils.OtherUserRequestUtils;
import com.umeng.community.example.Utils.ThirdLoginRequestUtils;
import com.umeng.community.example.Utils.UserRequestUtils;
import com.umeng.community.example.bean.MyInfo;

/**
 * Created by summersoft on 2016/5/10.
 */
public class UserInfoFragment extends BaseFragment<Void, NullPresenter> implements View.OnClickListener,
        MvpUserInfoView {

    /**
     * 已发送Feed的Fragment
     */
//    private PostedFeedsFragment mPostedFragment = null;

    /**
     * 关注的好友Fragment
     */
//    private FollowedUserFragment mFolloweredUserFragment;

    /**
     * 粉丝Fragment
     */
    private FansFragment mFansFragment;

    protected TextView mUserNameTv;
    private RoundImageView mHeaderImageView;
    protected ImageView mGenderImageView;
    protected ImageView mFollowToggleButton;

    /**
     * 已经发布的消息标签, 用于切换Fragment
     */
    private TextView mPostedTv;
    /**
     * 已经发布的消息数量标签
     */
    protected TextView mPostedCountTv;
    /**
     * 已经关注的用户标签, 用于切换Fragment
     */
    protected TextView mFollowedUserTv;

    /**
     * 已经关注的用户数量标签
     */
    protected TextView mFollowedUserCountTv;
    /**
     * 我的粉丝标签, 用于切换Fragment
     */
    protected TextView mFansTextView;
    /**
     * 我的fans用户数量标签
     */
    protected TextView mFansCountTextView;

    protected CommentEditText mCommentEditText;

    protected View mCommentLayout;

//    protected int mSelectedColor = Color.BLUE;
    /**
     * 相册TextView
     */
    protected TextView mAlbumTextView;
    /**
     * 话题TextView
     */
    protected TextView mTopicTextView;

    /**
     * 用户信息的Presenter
     */
    protected UserInfoPresenter mPresenter;

    protected View mHeaderView;
    protected View mTitleView;
    protected View messageBtn;
    /**
     * 举报用户的Dialog
     */
    protected UserReportDialog mReportDialog;

    protected View mTabCursor;
    protected int mScreenWidth;
    protected int mCurrentTab;
    protected LinearLayout typeContainer;
    protected SquareImageView mUserMedalImg;
    protected ImgDisplayOption mUserMedalImgOption;


    /**
     * Fragment管理器
     */
    private FragmentManager mFragmentManager = null;
    /**
     * Fragment的parent view,即Fragment的容器
     */
    protected int mFragmentContainer;
    /**
     * 当前显示的Fragment
     */
    public Fragment mCurrentFragment;


    /**
     * 该用户为传递进来的user，可能是好友、陌生人等身份
     */
    protected CommUser mUser;

    //我的收藏
    private TextView mCollectTV;
    //兴趣
    private TextView mInterestTV;
    //特长
    private TextView mSpecialtyTV;
    //学校
    private TextView mSshool;
    //年龄
    private TextView mAge;
    //我的收藏fragment
    private FavoritesFragment mFavoritesFragment;
    //设置
    private View mSetting;
    //发布页面
    private ReleaseFragment mReleaseFragment;
    //关注页面
    private FocusFragment mFocusFragment;

    private int selectPs = 0;

    private MyInfo info;

    private boolean isOther = false;

    public void setIsOther(boolean isOther) {
        this.isOther = isOther;
    }

    private CommUser user;
    //其他用户的source
    private String mSource;

    private CommunitySDK mSdkImpl;

    public void setUser(CommUser user) {
        this.user = user;
    }

    //个人信息layout
    private LinearLayout mInfo;

    //向左的图片按钮
    private ImageView mArrow;
    //返回键
    private ImageView mBack;

    public static boolean isRefresh = false;

    @Override
    protected void initWidgets() {

        if (isOther) {
            mUser = user;
            fetchUserProfile(); // 获取友盟用户数据
        } else {
            if (TextUtils.isEmpty(SPUtil.getInstance().getToken()) || !CommonUtils.isLogin(getActivity())) {//没有登录就没必要初始化
                return;
            } else {
                mUser = CommConfig.getConfig().loginedUser;
            }

        }
        if (mUser == null) {
            return;
        }
//        mFragmentManager = getActivity().getSupportFragmentManager();
        mFragmentManager = getChildFragmentManager();
        mUserMedalImgOption = new ImgDisplayOption();
        mPresenter = new UserInfoPresenter(getActivity(), this, mUser);
        //获取服务端的信息
        if (!isOther) {
            UserRequestUtils.getInstance(getActivity()).loadInfo(new UserRequestUtils.GetUserInfoListener() {
                @Override
                public void setUserInfo(MyInfo myInfo) {
                    info = myInfo;
                    setData();
                }
            });
        }

        typeContainer = (LinearLayout) findViewById(ResFinder.getId("user_type_icon_container"));
        // 初始化UI
        initUIComponents();
        initFragment();
        mPresenter.onCreate(getArguments());
        // 设置用户信息View的显示内容
        setupUserInfo(mUser);
//        Log.e("com.draw","info = " + info);
        initHeaderView();
        BroadcastUtils.registerFeedBroadcast(getActivity().getApplicationContext(), mReceiver);
        BroadcastUtils.registerUserBroadcast(getActivity().getApplicationContext(), mReceiver);

//        mRootView.setFocusable(true);//这个和下面的这个命令必须要设置了，才能监听back事件。
//        mRootView.setFocusableInTouchMode(true);
//        mRootView.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//                if (event.getAction() == KeyEvent.ACTION_DOWN) {
//                    if (keyCode == KeyEvent.KEYCODE_HOME) {  //表示按返回键 时的操作
//                        isOnclick = true;
//                        return true;    //已处理
//                    }
//                }
//                return false;
//            }
//        });

//        mRootView.setFocusable(true);//这个和下面的这个命令必须要设置了，才能监听back事件。
//        mRootView.setFocusableInTouchMode(true);
//        mRootView.setOnKeyListener(backlistener);

    }

    public void initFragment() {

        Log.i("ss", "initFragment");


        FragmentTransaction transaction = mFragmentManager.beginTransaction();


        switch (selectPs) {
            case 0:
                if (mReleaseFragment == null) {//首次进入
                    mReleaseFragment = new ReleaseFragment();
                    mReleaseFragment.setUserRelase(mUser);
                    addFragment(ResFinder.getId("umeng_comm_user_fragment_container"),
                            mReleaseFragment);
                } else {
                    transaction.remove(mReleaseFragment);
                    if (mFragmentManager.findFragmentByTag(mReleaseFragment.getClass().getName()) == null) {
                        transaction
                                .add(mFragmentContainer, mReleaseFragment, mReleaseFragment.getClass().getName());
                    } else {
                        mReleaseFragment = new ReleaseFragment();
                        mReleaseFragment.setUserRelase(mUser);
                        transaction
                                .add(mFragmentContainer, mReleaseFragment, mReleaseFragment.getClass().getName());
//                        transaction.show(mReleaseFragment);
                    }
                    transaction.commitAllowingStateLoss();

                    mCurrentFragment = mReleaseFragment;//重新进来后，点击切换分类会
//                    mFragmentContainer = ResFinder.getId("umeng_comm_user_info_fragment_container");
                }

                break;
            case 1:
                if (mFocusFragment != null)
                    transaction.remove(mFocusFragment);

                if (mFragmentManager.findFragmentByTag(mFocusFragment.getClass().getName()) == null) {
                    transaction
                            .add(mFragmentContainer, mFocusFragment, mFocusFragment.getClass().getName());
                } else {
//                    transaction.show(mFocusFragment);
                    mFocusFragment = new FocusFragment();
                    mFocusFragment.setUserFocus(mUser);
                    transaction
                            .add(mFragmentContainer, mFocusFragment, mFocusFragment.getClass().getName());
                }
                transaction.commitAllowingStateLoss();

                mCurrentFragment = mFocusFragment;
                break;
            case 2:
                if (mFragmentManager.findFragmentByTag(mFansFragment.getClass().getName()) == null) {
                    transaction
                            .add(mFragmentContainer, mFansFragment, mFansFragment.getClass().getName());
                } else {
                    mFansFragment = FansFragment.newFansFragment(mUser.id);
                    mFansFragment.setOnAnimationResultListener(mListener);
                    mFansFragment.setOnResultListener(mFansListener);

                    transaction
                            .add(mFragmentContainer, mFansFragment, mFansFragment.getClass().getName());
                }
                transaction.commitAllowingStateLoss();

                mCurrentFragment = mFansFragment;
                break;
        }
        changeSelectedText();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isRefresh) {
            isRefresh = false;
            UserRequestUtils.getInstance(getActivity()).loadInfo(new UserRequestUtils.GetUserInfoListener() {
                @Override
                public void setUserInfo(MyInfo myInfo) {
                    info = myInfo;
                    setData();
                }
            });
        }
    }

    @Override
    protected int getFragmentLayout() {
        return ResFinder.getLayout("userinfo_fragment");
    }

    private void ListenerSet() {
        mFollowToggleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(SPUtil.getInstance().getToken()) || !CommonUtils.isLogin(getActivity())) {

                    CommunitySDKImpl.getInstance().login(getActivity(), new LoginListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onComplete(int stCode, CommUser userInfo) {

                            if (stCode == 0) {
                                ThirdLoginRequestUtils.getInstance(getActivity()).ThirdLogin(userInfo);
                                mFollowToggleButton.setClickable(false);
                                // true为选中状态为已关注，此时显示文本为“取消关注”；false代表未关注，此时显示文本为“关注”
                                if (!mUser.isFollowed) {
                                    mPresenter.followUser(mResultListener);
                                } else {
                                    mPresenter.cancelFollowUser(mResultListener);
                                }
                            }
                        }
                    });
                } else {
                    mFollowToggleButton.setClickable(false);
                    // true为选中状态为已关注，此时显示文本为“取消关注”；false代表未关注，此时显示文本为“关注”
                    if (!mUser.isFollowed) {
                        mPresenter.followUser(mResultListener);
                    } else {
                        mPresenter.cancelFollowUser(mResultListener);
                    }
                }
            }
        });
        mAlbumTextView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                jumpToActivityWithUid(com.umeng.comm.ui.imagepicker.activities.AlbumActivity.class);
            }
        });
        mTopicTextView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                jumpToActivityWithUid(FollowedTopicActivity.class);
            }
        });
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (id == ResFinder.getId("umeng_comm_posted_layout")) {// 已发消息

            transaction.remove(mReleaseFragment);
            if (mFragmentManager.findFragmentByTag(mReleaseFragment.getClass().getName()) == null) {
                transaction
                        .add(mFragmentContainer, mReleaseFragment, mReleaseFragment.getClass().getName());
            } else {
                mReleaseFragment = new ReleaseFragment();
                mReleaseFragment.setUserRelase(mUser);
                transaction
                        .add(mFragmentContainer, mReleaseFragment, mReleaseFragment.getClass().getName());
//                        transaction.show(mReleaseFragment);
            }
            transaction.commitAllowingStateLoss();
            mCurrentFragment = mReleaseFragment;//重新进来后，点击切换分类会
            updateFeedTextView(mUser.feedCount);
            selectPs = 0;
        } else if (id == ResFinder.getId("umeng_comm_follow_user_layout")) {// 关注用户

            if (mFocusFragment == null) {
                mFocusFragment = new FocusFragment();
                mFocusFragment.setUserFocus(mUser);
                showFragment(mFocusFragment);
            } else {
                transaction.remove(mFocusFragment);

                if (mFragmentManager.findFragmentByTag(mFocusFragment.getClass().getName()) == null) {
                    transaction
                            .add(mFragmentContainer, mFocusFragment, mFocusFragment.getClass().getName());
                } else {
                    mFocusFragment = new FocusFragment();
                    mFocusFragment.setUserFocus(mUser);
                    transaction
                            .add(mFragmentContainer, mFocusFragment, mFocusFragment.getClass().getName());
                }
                transaction.commitAllowingStateLoss();

                mCurrentFragment = mFocusFragment;
            }
            selectPs = 1;
        } else if (id == ResFinder.getId("umeng_comm_my_fans_layout")) { // 我的粉丝

            if (mFocusFragment != null) {
                mFocusFragment.removeAllFragment();
            }
            if (mReleaseFragment != null) {
                mReleaseFragment.removeAllFragment();
            }
            if (mFansFragment == null) {
                mFansFragment = FansFragment.newFansFragment(mUser.id);
                mFansFragment.setOnAnimationResultListener(mListener);
                mFansFragment.setOnResultListener(mFansListener);
                showFragment(mFansFragment);
            } else {
                transaction.remove(mFansFragment);

                if (mFragmentManager.findFragmentByTag(mFansFragment.getClass().getName()) == null) {
                    transaction
                            .add(mFragmentContainer, mFansFragment, mFansFragment.getClass().getName());
                } else {
                    mFansFragment = FansFragment.newFansFragment(mUser.id);
                    mFansFragment.setOnAnimationResultListener(mListener);
                    mFansFragment.setOnResultListener(mFansListener);

                    transaction
                            .add(mFragmentContainer, mFansFragment, mFansFragment.getClass().getName());
                }
                transaction.commitAllowingStateLoss();

                mCurrentFragment = mFansFragment;
            }
            selectPs = 2;
        } else if (id == ResFinder.getId("umeng_comm_title_back_btn")) { // 返回
            getActivity().finish();
        }
        changeSelectedText();
    }


    /**
     * 修改文本颜色 </br>
     */
    protected void changeSelectedText() {
        if ((mCurrentFragment instanceof ReleaseFragment)) {
            changeTextColor(true, false, false);
        } else if ((mCurrentFragment instanceof FansFragment)) {
            changeTextColor(false, false, true);
        } else if ((mCurrentFragment instanceof FocusFragment)) {
            changeTextColor(false, true, false);
        }
    }

    protected void ReceiverComplete(CommUser user, boolean follow) {
//        if (mFolloweredUserFragment != null) {
//            if(CommonUtils.isLogin(getActivity())){
//                mFolloweredUserFragment.updateFollowedState(user.id, follow);
//            }
//        }
        if (mFansFragment != null) {
            if (CommonUtils.isLogin(getActivity())) {
                mFansFragment.updateFollowedState(user.id, follow);
            }
        }
    }

//    protected void initCommentView() {
//        mCommentEditText = mViewFinder.findViewById(ResFinder
//                .getId("umeng_comm_comment_edittext"));
//        mCommentLayout = findViewById(ResFinder.getId("umeng_comm_commnet_edit_layout"));
//
//        findViewById(ResFinder.getId("umeng_comm_comment_send_button")).setOnClickListener(this);
//        mCommentEditText.setEditTextBackListener(new CommentEditText.EditTextBackEventListener() {
//
//            @Override
//            public boolean onClickBack() {
//                hideCommentLayout();
//                return true;
//            }
//        });
//    }

    /**
     * 隐藏评论布局</br>
     */
    protected void hideCommentLayout() {
        mCommentLayout.setVisibility(View.GONE);
//        hideInputMethod(mCommentEditText);
    }

    @SuppressWarnings("deprecation")
    protected void initUIComponents() {
        // 设置Fragment
//        addFragment(ResFinder.getId("umeng_comm_user_info_fragment_container"),
//                mPostedFragment);

        // 选中的某个tab时的文字颜色
//        mSelectedColor = ResFinder.getColor("umeng_comm_text_topic_light_color");

        // 初始化feed、好友、粉丝、back、设置的listener
        findViewById(ResFinder.getId("umeng_comm_posted_layout")).setOnClickListener(this);
        findViewById(ResFinder.getId("umeng_comm_follow_user_layout")).setOnClickListener(
                this);
        findViewById(ResFinder.getId("umeng_comm_my_fans_layout")).setOnClickListener(this);
        mBack = findViewById(ResFinder.getId("umeng_comm_title_back_btn"));
        mBack.setOnClickListener(this);

        // 举报用户的Dialog
        mReportDialog = new UserReportDialog(getActivity());
        mReportDialog.setTargetUid(mUser.id);

        messageBtn = findViewById(ResFinder.getId("umeng_comm_title_chat_btn"));
        CommUser mLoginedUser = CommConfig.getConfig().loginedUser;
        if (mLoginedUser != null && !mLoginedUser.id.equals(mUser.id)
                && (mUser.permisson == CommUser.Permisson.ADMIN
                || mUser.permisson == CommUser.Permisson.SUPPER_ADMIN
                || mLoginedUser.permisson == CommUser.Permisson.SUPPER_ADMIN
                || mLoginedUser.permisson == CommUser.Permisson.ADMIN)) {
            messageBtn.setVisibility(View.GONE);
            messageBtn.setOnClickListener(new Listeners.LoginOnViewClickListener() {
                                              @Override
                                              protected void doAfterLogin(View v) {
                                                  Intent i = new Intent(getActivity(), MessageChatActivity.class);
                                                  i.putExtra("uid", mUser.id);
                                                  i.putExtra("userName", mUser.name);
                                                  getActivity().startActivity(i);
                                              }
                                          }
//            {
//                @Override
//                public void onClick(View view) {
//                    Intent i = new Intent(UserInfoActivity.this, MessageChatActivity.class);
//                    i.putExtra("uid", mUser.id);
//                    i.putExtra("userName", mUser.name);
//                    UserInfoActivity.this.startActivity(i);
//                }
//            }
            );
        } else {
            messageBtn.setVisibility(View.GONE);
        }

        View settingButton = findViewById(ResFinder.getId("umeng_comm_title_more_btn"));
        if (mUser.permisson == CommUser.Permisson.ADMIN) {
            settingButton.setVisibility(View.GONE);
        }
        settingButton.setOnClickListener(new Listeners.LoginOnViewClickListener() {

            @Override
            protected void doAfterLogin(View v) {
                mReportDialog.show();
            }
        });
        // 如果是用户自己，则不显示设置菜单按钮【目前菜单只有举报功能，即自己不能举报自己】
        if (mUser.id.equals(CommConfig.getConfig().loginedUser.id)
                || mUser.permisson == CommUser.Permisson.SUPPER_ADMIN) {
            settingButton.setVisibility(View.GONE);
            if (messageBtn.getVisibility() == View.VISIBLE) {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) messageBtn.getLayoutParams();
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            }
        }

        //
        mPostedTv = mViewFinder.findViewById(ResFinder.getId("umeng_comm_posted_msg_tv"));
//        mPostedTv.setTextColor(mSelectedColor);
        mPostedTv.setSelected(true);


        //
        mPostedCountTv = mViewFinder.findViewById(ResFinder
                .getId("umeng_comm_posted_count_tv"));
//        mPostedCountTv.setTextColor(mSelectedColor);
        mPostedCountTv.setSelected(true);
        mPostedCountTv.setVisibility(View.GONE);

        mFollowedUserTv = mViewFinder.findViewById(ResFinder.getId(
                "umeng_comm_followed_user_tv"));
        mFollowedUserCountTv = mViewFinder.findViewById(ResFinder.getId(
                "umeng_comm_follow_user_count_tv"));
        mFollowedUserCountTv.setVisibility(View.GONE);
        mFansTextView = mViewFinder.findViewById(ResFinder.getId("umeng_comm_my_fans_tv"));
        mFansCountTextView = mViewFinder.findViewById(ResFinder.getId(
                "umeng_comm_fans_count_tv"));
        mFansCountTextView.setVisibility(View.GONE);
        // 昵称
        mUserNameTv = mViewFinder.findViewById(ResFinder.getId("umeng_comm_user_name_tv"));
        mUserNameTv.setText(mUser.name);

        mHeaderImageView = mViewFinder.findViewById(ResFinder.getId(
                "umeng_comm_user_header"));
        mHeaderImageView.setBackGroundColor(ResFinder.getColor("umeng_comm_color_transparent"));

        ImgDisplayOption option = ImgDisplayOption.getOptionByGender(mUser.gender);
        mHeaderImageView.setImageUrl(mUser.iconUrl, option);
        // 用户性别
        mGenderImageView = mViewFinder.findViewById(ResFinder.getId("umeng_comm_user_gender"));

        // 关注按钮
        mFollowToggleButton = mViewFinder.findViewById(ResFinder.getId(
                "umeng_comm_user_follow"));


        mAlbumTextView = mViewFinder.findViewById(ResFinder.getId("umeng_comm_user_albums_tv"));
        mTopicTextView = mViewFinder.findViewById(ResFinder.getId("umeng_comm_user_topic_tv"));

        mCollectTV = mViewFinder.findViewById(ResFinder.getId("collect_tv"));
        mCollectTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().startActivity(new Intent(getActivity(), FavoritesActivity.class));
            }
        });
        mInterestTV = mViewFinder.findViewById(ResFinder.getId("interest_tv"));
        mSpecialtyTV = mViewFinder.findViewById(ResFinder.getId("specialty_tv"));
        mSshool = mViewFinder.findViewById(ResFinder.getId("user_grade"));
        mAge = mViewFinder.findViewById(ResFinder.getId("user_age"));
        mSetting = findViewById(ResFinder.getId("umeng_comm_title_set_btn"));
        mSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().startActivity(new Intent(getActivity(), SetActivity.class));
            }
        });

        mInfo = findViewById(ResFinder.getId("umeng_comm_portrait_layout"));
        mArrow = findViewById(ResFinder.getId("btn_arrow"));


        if (isOther && !mUser.id.equals(CommConfig.getConfig().loginedUser.id)) {
            mSetting.setVisibility(View.GONE);
            mArrow.setVisibility(View.GONE);
            mBack.setVisibility(View.VISIBLE);
            mCollectTV.setVisibility(View.GONE);
        } else {
            if (isOther) {
                mBack.setVisibility(View.VISIBLE);
            } else {
                mBack.setVisibility(View.GONE);
            }
            mArrow.setVisibility(View.VISIBLE);
            mSetting.setVisibility(View.VISIBLE);
            mCollectTV.setVisibility(View.VISIBLE);
            mInfo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SettingActivity.actionStart(getActivity(), true);
                }
            });
        }

        // 用户自己(在未登录的情况下，点击设置跳转到登录，此时传递进来的uid是空的情况)，隐藏关注按钮，显示设置按钮
        // // 如果是超级管理员且已经关注，则隐藏取消关注按钮
        if (isHideFollowStatus()) {
            mFollowToggleButton.setVisibility(View.GONE);
        }
//        initCommentView();

        mScreenWidth = DeviceUtils.getScreenSize(getActivity().getApplicationContext()).x;
        mTabCursor = findViewById(ResFinder.getId("umeng_comm_tab_cursor"));

        mUserMedalImg = mViewFinder.findViewById(ResFinder.getId("user_comm_user_medal_img"));
        ListenerSet();
    }

    /**
     * 显示收藏Feed</br>
     */
//    protected void showFavoritesFeed() {
//        if (mFavoritesFragment == null) {
//            mFavoritesFragment = FavoritesFragment.newFavoritesFragment();
//            mFavoritesFragment.setOnResultListener(new Listeners.OnResultListener() {
//
//                @Override
//                public void onResult(int status) {
//                    showFindPage();
//                }
//            });
//        }
//        showCommFragment(mFavoritesFragment);
//    }

    /**
     * 隐藏发现页面，显示fragment</br>
     *
     * @param fragment
     */
//    protected void showCommFragment(Fragment fragment) {
//        findViewById(ResFinder.getId("user_lay")).setVisibility(View.GONE);
//        int container = ResFinder.getId("user_container");
//        findViewById(container).setVisibility(View.VISIBLE);
//        setFragmentContainerId(container);
//        showFragmentInContainer(container, fragment);
//    }

    /**
     * 隐藏fragment，显示发现页面</br>
     */
//    protected void showFindPage() {
//        findViewById(ResFinder.getId("user_lay")).setVisibility(
//                View.VISIBLE);
//        findViewById(ResFinder.getId("user_container")).setVisibility(View.GONE);
//    }

    /**
     * 需要在调用任何函数前设置
     *
     * @param container 用于放置fragment的布局id
     */
    public void setFragmentContainerId(int container) {
        mFragmentContainer = container;
    }

    protected boolean isHideFollowStatus() {
        if (TextUtils.isEmpty(mUser.id)) {
            return true;
        }
        CommUser loginUser = CommConfig.getConfig().loginedUser;
        if (mUser.id.equals(loginUser.id)) { // 如果是用户自己，则不显示关注/取消关注
            return true;
        }
        // 如果是超级管理员且已经被关注，则显示关注/取消关注
        if (mUser.permisson == CommUser.Permisson.SUPPER_ADMIN && mUser.isFollowed) {
            return true;
        }
        return false;
    }

    protected void initHeaderView() {
        mHeaderView = findViewById(ResFinder.getId("umeng_comm_portrait_layout"));
        mHeaderView.getViewTreeObserver().addOnGlobalFocusChangeListener(mChangeListener);
        mTitleView = findViewById(ResFinder.getId("umeng_comm_title_layout"));
    }

    protected CustomAnimator mCustomAnimator = new UserInfoAnimator();
    protected Listeners.OnResultListener mListener = new Listeners.OnResultListener() {

        @Override
        public void onResult(int status) {
            if (status == 1) {// dismiss
                mCustomAnimator.startDismissAnimation(mHeaderView);
            } else if (status == 0) { // show
                mCustomAnimator.startShowAnimation(mHeaderView);
            }
        }
    };

    protected ViewTreeObserver.OnGlobalFocusChangeListener mChangeListener = new ViewTreeObserver.OnGlobalFocusChangeListener() {

        @Override
        public void onGlobalFocusChanged(View oldFocus, View newFocus) {
            int pos = mHeaderView.getHeight() - mHeaderView.getPaddingTop()
                    + mTitleView.getHeight() / 2;
            mCustomAnimator.setStartPosition(pos);
            mHeaderView.getViewTreeObserver().removeOnGlobalFocusChangeListener(mChangeListener);
        }
    };

    protected void jumpToActivityWithUid(Class<?> activityClass) {
        Intent intent = new Intent(getActivity().getApplicationContext(), activityClass);
        intent.putExtra(Constants.USER_ID_KEY, mUser.id);
        startActivity(intent);
    }

    /**
     * 避免对此点击，在回调中将状态设置为可点击状态~
     */
    protected Listeners.OnResultListener mResultListener = new Listeners.OnResultListener() {

        @Override
        public void onResult(int status) {
            mFollowToggleButton.setClickable(true);
        }
    };

//    protected void moveTabCurosr(int position) {
//        int endPosition = 0;
//        int startPosition = 0;
//        int distance = (mScreenWidth - CommonUtils.dip2px(getActivity().getApplicationContext(), 34 * 2 + 32 * 3)) / 2;
//
//        switch (mCurrentTab) {
//            case 0:
//                startPosition = 0;
//                break;
//            case 1:
//                startPosition = CommonUtils.dip2px(getActivity().getApplicationContext(), 32) + distance;
//                break;
//            case 2:
//                startPosition = CommonUtils.dip2px(getActivity().getApplicationContext(), 32 * 2) + distance * 2;
//                break;
//            default:
//                break;
//        }
//
//        switch (position) {
//            case 0:
//                endPosition = 0;
//                break;
//            case 1:
//                endPosition = CommonUtils.dip2px(getActivity().getApplicationContext(), 32) + distance;
//                break;
//            case 2:
//                endPosition = CommonUtils.dip2px(getActivity().getApplicationContext(), 32 * 2) + distance * 2;
//                break;
//            default:
//                break;
//        }
//        mCurrentTab = position;
//        TranslateAnimation animation = new TranslateAnimation(startPosition, endPosition, 0, 0);
//        animation.setDuration(200);//设置动画持续时间
//        animation.setFillAfter(true);
//        mTabCursor.startAnimation(animation);
//    }

    /**
     * 设置用户相关的信息 </br>
     *
     * @param user
     */
    @Override
    public void setupUserInfo(CommUser user) {
        if (!user.id.equals(mUser.id)) {
            return;
        }
        mUser = user;
        mUserNameTv.setText(user.name);
        if (user.gender == CommUser.Gender.MALE) {
            mGenderImageView.setSelected(false);
//            mGenderImageView.setImageDrawable(ResFinder.getDrawable("umeng_comm_user_info_male"));
        } else if (user.gender == CommUser.Gender.FEMALE) {
            mGenderImageView.setSelected(true);
//            mGenderImageView.setImageDrawable(ResFinder.getDrawable("umeng_comm_user_info_female"));
        }
        ImgDisplayOption option = ImgDisplayOption.getOptionByGender(user.gender);
        mHeaderImageView.setImageUrl(user.iconUrl, option);
//        mHeaderImageView.setImageDrawable(ResFinder.getDrawable("morentuf"));
        // 设置用户头像
//        if (TextUtils.isEmpty(user.iconUrl)){
//            mHeaderImageView.setImageDrawable(ResFinder.getDrawable("morentuf"));
//        }else {
//            mHeaderImageView.setImageUrl(user.iconUrl);
//        }


        ImageLoaderManager.getInstance().getCurrentSDK().resume();
        if (isHideFollowStatus()) {
            mFollowToggleButton.setVisibility(View.GONE);
        } else {
            mFollowToggleButton.setVisibility(View.VISIBLE);
            updataFollowBtnState();
        }

        TextView mScoreTextView = (TextView) findViewById(ResFinder.getId("umeng_comm_user_jifen_tv"));
        StringBuffer str = new StringBuffer(ResFinder.getString("umeng_comm_user_socre"));
        str.append(CommonUtils.getLimitedCount(mUser.point));
        mScoreTextView.setText(str.toString());

        UserTypeUtil.SetUserType(getActivity(), user, typeContainer);
    }

    private void setData() {
        mAge.setText(StringUtil.age(TimeUtil.getStrTime5(info.getBirthday())) + "岁");
        if (!TextUtils.isEmpty(info.getSchoolGrade())) {
            mSshool.setText(info.getSchoolGrade());
        } else {
            mSshool.setText("暂无学校信息");
        }
        if (!TextUtils.isEmpty(info.getInterest())) {
            mInterestTV.setText(info.getInterest());
        } else {
            mInterestTV.setText("暂无兴趣");
        }
        if (!TextUtils.isEmpty(info.getSpecialty())) {
            mSpecialtyTV.setText(info.getSpecialty());
        } else {
            mSpecialtyTV.setText("暂无特长");
        }
    }

    protected void updataFollowBtnState() {
        boolean isFollowed = mUser.isFollowed;
        boolean isFollowing = mUser.isFollowingMe;
        if (isFollowed && isFollowing) {
            mFollowToggleButton.setImageDrawable(ResFinder.getDrawable("zhuye_btn_huxiang"));
        } else if (isFollowed) {
            mFollowToggleButton.setImageDrawable(ResFinder.getDrawable("zhuye_btn_yijguanzhu"));
        } else {
            mFollowToggleButton.setImageDrawable(ResFinder.getDrawable("zhuye_btn_guanzhu"));
        }
    }

    /**
     * 设置文本颜色</br>
     *
     * @param postedColor 已发送feed文本颜色
     * @param followColor 关注文本颜色
     * @param fansColor   粉丝文本颜色
     */
    private void changeTextColor(boolean postedColor, boolean followColor, boolean fansColor) {
        mPostedTv.setSelected(postedColor);
        mPostedCountTv.setSelected(postedColor);
        mFollowedUserTv.setSelected(followColor);
        mFollowedUserCountTv.setSelected(followColor);
        mFansTextView.setSelected(fansColor);
        mFansCountTextView.setSelected(fansColor);
    }

    /**
     * 关注用户数的回调函数。在加载缓存或者下拉刷新时，可能需要更新显示的用户数字。
     */
    protected Listeners.OnResultListener mFollowListener = new Listeners.OnResultListener() {

        @Override
        public void onResult(final int status) {
            if (mPresenter.isUpdateFollowUserCountTextView()) {
                CommonUtils.runOnUIThread(getActivity(), new Runnable() {

                    @Override
                    public void run() {
                        mFollowedUserCountTv.setText(String.valueOf(status));
                    }
                });
            }
        }
    };

    /**
     * 粉丝数的回调函数。在加载缓存或者下拉刷新时，可能需要更新显示的用户数字。
     */
    protected Listeners.OnResultListener mFansListener = new Listeners.OnResultListener() {

        @Override
        public void onResult(final int status) {
            if (mPresenter.isUpdateFansCountTextView()) {
                CommonUtils.runOnUIThread(getActivity(), new Runnable() {

                    @Override
                    public void run() {
                        mFansCountTextView.setText(String.valueOf(status));
                    }
                });
            }
        }
    };

    @Override
    public void setToggleButtonStatus(boolean status) {
        mUser.isFollowed = status;
        updataFollowBtnState();
    }

    /**
     * 粉丝
     *
     * @param count
     */
    public void updateFansTextView(int count) {
        mFansCountTextView.setText(String.valueOf(CommonUtils.getLimitedCount(count)));
    }

    /**
     * 发布
     *
     * @param count
     */
    public void updateFeedTextView(int count) {
        mUser.feedCount = count;
        mPostedCountTv.setText(String.valueOf(CommonUtils.getLimitedCount(count)));
    }

    /**
     * 关注
     *
     * @param count
     */
    public void updateFollowTextView(int count) {
        mFollowedUserCountTv.setText(String.valueOf(CommonUtils.getLimitedCount(count)));
    }

    @Override
    public void onDestroy() {
        mPresenter.onDestroy();
        BroadcastUtils.unRegisterBroadcast(getActivity().getApplicationContext(), mReceiver);
        super.onDestroy();
    }

    /**
     * 数据同步处理
     */
    protected BroadcastUtils.DefalutReceiver mReceiver = new BroadcastUtils.DefalutReceiver() {

        public void onReceiveFeed(Intent intent) {// 发送or删除时
            FeedItem feedItem = getFeed(intent);
            if (feedItem == null || !CommonUtils.isMyself(mUser)) {
                return;
            }

            BroadcastUtils.BROADCAST_TYPE type = getType(intent);
            if (BroadcastUtils.BROADCAST_TYPE.TYPE_FEED_POST == type) {
                updateFeedTextView(++mUser.feedCount);
            }
        }

        @Override
        public void onReceiveUser(Intent intent) {
            CommUser newUser = getUser(intent);
            BroadcastUtils.BROADCAST_TYPE type = getType(intent);
            boolean follow = true;
            if (type == BroadcastUtils.BROADCAST_TYPE.TYPE_USER_FOLLOW) {
                follow = true;
            } else if (type == BroadcastUtils.BROADCAST_TYPE.TYPE_USER_CANCEL_FOLLOW) {
                follow = false;
            }
            ReceiverComplete(newUser, follow);
        }
    };

    private View.OnKeyListener backlistener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                if (i == KeyEvent.KEYCODE_BACK && mCommentLayout.isShown()) {  //表示按返回键 时的操作
                    mCommentLayout.setVisibility(View.VISIBLE);
                    return true;
                }
            }
            return false;
        }
    };

    /**
     * @param container 用于放置fragment的布局id
     * @param fragment  要添加的Fragment
     */
    public void addFragment(int container, Fragment fragment) {

        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        if (!isFragmentAdded(fragment)) {
            fragmentTransaction
                    .add(container, fragment,
                            fragment.getClass().getName()).commitAllowingStateLoss();
            mCurrentFragment = fragment;
        } else {
            fragmentTransaction.show(fragment).commitAllowingStateLoss();
        }

        mFragmentContainer = container;
    }


    /**
     * 判断一个Fragment是否已经添加
     *
     * @param fragment 要判断是否已经添加的Fragment
     * @return
     */
    public boolean isFragmentAdded(Fragment fragment) {
        return fragment != null
                && mFragmentManager.findFragmentByTag(fragment.getClass().getName()) != null;
    }

    /**
     * 显示Fragment，并且把上一个隐藏
     *
     * @param fragmentShow
     */
    public void showFragment(Fragment fragmentShow) {
        showFragmentInContainer(mFragmentContainer, fragmentShow);
    }

    /**
     * 将fragmentShow显示在一个新的container上,而不覆盖mFragmentContainer。
     * 这种情况适用于Fragment中又嵌套Fragment
     *
     * @param container
     * @param fragmentShow
     */
    public void showFragmentInContainer(int container, Fragment fragmentShow) {
        checkContainer();

        if (mCurrentFragment != fragmentShow) {
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            if (mCurrentFragment != null) {
                // 首先隐藏原来显示的Fragment
                transaction.hide(mCurrentFragment);
            }
            // 然后再显示传递进来的Fragment
            if (mFragmentManager.findFragmentByTag(fragmentShow.getClass().getName()) == null) {
                transaction
                        .add(container, fragmentShow, fragmentShow.getClass().getName());
            } else {
//                transaction.show(fragmentShow);
                transaction.remove(fragmentShow);
                transaction
                        .add(container, fragmentShow, fragmentShow.getClass().getName());
            }
            transaction.commitAllowingStateLoss();
            mCurrentFragment = fragmentShow;
        }
    }

    /**
     * 检查放置fragment的布局id
     */
    private void checkContainer() {
        if (mFragmentContainer <= 0) {
            throw new RuntimeException(
                    "在调用replaceFragment函数之前请调用setFragmentContainerId函数来设置fragment container id");
        }
    }

    /**
     * 获取其他用户信息
     */
    private void fetchUserProfile() {
        if (user == null || TextUtils.isEmpty(user.id)) {
            LogUtil.e("mUser为空 或 mUser.id为空！");
            return;
        }
        if (mSdkImpl == null) {
            mSdkImpl = CommunityFactory.getCommSDK(getActivity());
        }
        LogUtil.e("触发~~~");
        mSdkImpl.fetchUserProfile(user.id, new Listeners.FetchListener<ProfileResponse>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onComplete(ProfileResponse response) {
                if (NetworkUtils.handleResponseAll(response)) {
                    return;
                }
                mUser = response.result;
                mSource = response.source;
                Log.e("com.draw", "mUser =" + mUser);
                Log.e("com.draw", "openId =" + mUser.sourceUid);
                Log.e("com,draw", "type = " + mUser.source);
                OtherUserRequestUtils.getInstance(getActivity()).OtherUser(mUser, mSource, new OtherUserRequestUtils.GetOtherUserInfoListener() {
                    @Override
                    public void setOtherUserInfo(MyInfo myInfo) {
                        info = myInfo;
                        setData();
                    }
                });
                LogUtil.e("response = " + response);
                LogUtil.e("user.sourceUid = " + response.sourceUid + " || user.source = " + response.source);
                // TODO
//                DatabaseAPI.getInstance().getUserDBAPI().saveUserInfoToDB(user);
            }
        });

    }

}
